package com.amkai.aes.webservice.binary.objecthandler;

import java.io.Serializable;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.Query;

import com.amkai.aes.aescommon.factory.RADBeanFactory;
import com.amkai.aes.aescommon.service.binary.job.DesktopContentJob;
import com.amkai.aes.aescommon.service.binary.job.DesktopContentKind;
import com.amkai.aes.aescommon.service.result.DesktopContentResult;
import com.amkai.aes.generatedbeans.organization.Department;
import com.amkai.aes.generatedbeans.passport.DesktopContent;
import com.amkai.aes.generatedbeans.passport.Passport;
import com.amkai.aes.server.session.ServiceSessionManager;
import com.amkai.aes.webservice.binary.JobObjectHandler;
import com.amkai.common.extensions.hibernate.config.SiteManager;
import com.amkai.common.extensions.hibernate.config.manager.SessionManager;
import com.amkai.rad.designerbase.beans.ChangedKind;

public class DesktopContentHandler implements 
	JobObjectHandler<DesktopContentJob, Serializable, DesktopContentResult> {

	private static final Log log = LogFactory.getLog(DesktopContentHandler.class);

	
	public DesktopContentResult process(DesktopContentJob job, Serializable object) throws Exception {
		DesktopContentResult result = new DesktopContentResult();
		result.setDcKind(job.getContentKind());

		Passport runtimePassport = ServiceSessionManager.getConnection().getRuntimePassport();
		if (runtimePassport == null) {
			return result;
		}

		SessionManager sm = SiteManager.Start();
		try {
			sm.openTransaction();
			Passport passport = sm.load(Passport.class, runtimePassport.getId());
			
			Department runtimeDepartment = job.getModuleDepartment();
			// KKORNEL: AES-6856
			if ((runtimeDepartment != null) && (passport != null)) {
				Department department = sm.load(Department.class, runtimeDepartment.getId());
				
				Query q = sm.execute("from DesktopContent where baseOrganization = :baseOrganization and passport = :passport");
				q.setEntity("baseOrganization", department);
				q.setEntity("passport", passport);
				DesktopContent dc = (DesktopContent) q.uniqueResult();
				if (dc == null)  { 
					dc = createDesktopContentForPassport(passport, sm, job);				
				}  
	//			else {
	//				dc = sm.get(DesktopContent.class, dc.getId());
	//			}
				
				if (job.getContentKind() == DesktopContentKind.CLEAR_CONTENT) {
					clearDesktopContent(passport, dc,sm);				
				} else {
				
					if (job.getContent() == null) {			
						//read content from DB
						switch (job.getContentKind())  {
							case LAYOUT : {
								result.setContent(dc.getLayout());
								break;
							}
							case MODULESCONTENT : {
								result.setContent(dc.getModulesContent());
								break;
							}
						}
					} else {
										
						//write content into DB	
						switch (job.getContentKind())  {
							case LAYOUT : {
								dc.setLayout(job.getContent());
								break;
							}
							case MODULESCONTENT : {
								dc.setModulesContent(job.getContent());
								break;
							}
						}
						sm.saveRAD(dc);
					}
				}
			}
			sm.commitTransaction();
				
		} catch (Exception e) {		
			sm.rollbackTransaction();
			log.error("", e);
			throw e;
			// TODO: handle exception
		} finally {
			sm.closeSession();
		}
		
		return result;
	}

	private void clearDesktopContent(Passport pass, DesktopContent dc, SessionManager sm) {
		if (dc.getChangedKind() == ChangedKind.CREATED) return;
		
		dc.setChangedKind(ChangedKind.DELETED);
		
		sm.saveRAD(dc);
	}

	private DesktopContent createDesktopContentForPassport(Passport originPassport, SessionManager sm, DesktopContentJob job) throws Exception {
		Passport passport = getOriginPassport(originPassport.getId(), sm);
		DesktopContent dc = RADBeanFactory.getInstance().createBean(DesktopContent.class);
		dc.setPassport(originPassport);
		
		Department runtimeDepartment = job.getModuleDepartment();
		Department department = sm.load(Department.class, runtimeDepartment.getId());
		
		dc.setBaseOrganization(department);
		sm.saveRAD(dc);

		return dc;
	}
	
	
	private Passport getOriginPassport(Long id, SessionManager sm) throws Exception {
		Passport passport = sm.get(Passport.class, id);
		return passport;
	}

}
